package com.welfare.util;

import com.welfare.common.sql.JdbcUtil;
import com.welfare.common.utils.StringUtils;
import com.welfare.generator.config.GenConfig;
import com.welfare.generator.domain.GenTable;
import com.welfare.generator.domain.GenTableColumn;
import com.welfare.generator.mapper.GenTableColumnMapper;
import com.welfare.generator.mapper.GenTableMapper;
import com.welfare.generator.service.IGenTableService;
import com.welfare.generator.util.GenUtils;
import com.welfare.generator.util.VelocityInitializer;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.welfare.generator.util.GenUtils.convertClassName;
import static com.welfare.generator.util.GenUtils.getModuleName;

/**
 * @author dong
 * @date 2022-08-22 09:37
 */
@Component
public class GenHandUtils {
    @Autowired
    GenConfig genConfig;

    @Autowired
    private GenTableMapper genTableMapper;

    @Autowired
    private GenTableColumnMapper genTableColumnMapper;

    @Autowired
    private IGenTableService genTableService;

    public void  gen() throws SQLException {
        VelocityInitializer.initVelocity();

        String operName = "system_bath";
        StringBuilder sql=new StringBuilder();
        sql.append("SELECT table_name,column_name,column_type,data_type,column_comment,column_key,extra,(ordinal_position) as sort");
        sql.append(" ,(case when (is_nullable = 'no' && column_key != 'PRI') then '1' else null end) as is_required");
        sql.append(" ,(case when column_key = 'PRI' then '1' else '0' end) as is_pk");
        sql.append(" ,(case when extra = 'auto_increment' then '1' else '0' end) as is_increment");
        sql.append("  FROM  INFORMATION_SCHEMA.Columns");
        sql.append(" where TABLE_SCHEMA ='");
        sql.append(GenConfig.getDataBase());
        sql.append("'");
        if(!StringUtils.isEmpty(GenConfig.getTablePrefix())){
            sql.append(" and TABLE_NAME like '"+GenConfig.getTablePrefixBath()+"%' ");
        }
        else {
            String tableIn = GenConfig.getTableIn();
            StringBuffer tableStr = new StringBuffer("");
            String[] split = tableIn.split(",");
            for(String table : split) {
                tableStr.append("'").append(table).append("'").append(",");
            }
            sql.append(" and TABLE_NAME in ("+tableStr.toString().substring(0,tableStr.toString().length()-1)+") ");
        }

        StringBuilder table_sql=new StringBuilder();
        table_sql.append("SELECT  table_name,table_comment FROM  information_schema.TABLES WHERE TABLE_SCHEMA = '");
        table_sql.append(GenConfig.getDataBase());
        table_sql.append("'");
        JdbcUtil jdbcUtil = new JdbcUtil(GenConfig.getJdbcDriver(), GenConfig.getJdbcUrl(), GenConfig.getJdbcUserName(),GenConfig.getJdbcPwd());
        List<Map> result = jdbcUtil.selectByParams(sql.toString(), null);
        List<Map> tableResult=jdbcUtil.selectByParams(table_sql.toString(),null);
        Map<String, List<Map>> singleMap = result.stream().collect(Collectors.groupingBy(g->g.get("table_name").toString()));
        List<String> tableNames=new ArrayList<>();
        for (Map.Entry entry : singleMap.entrySet()) {
            String tableName =entry.getKey().toString();
            tableNames.add(tableName);
            GenTable genTable=new GenTable();
            genTable.setClassName(convertClassName(tableName));
            genTable.setPackageName(GenConfig.getPackageName());
            genTable.setModuleName(getModuleName(GenConfig.getPackageName()));
            genTable.setBusinessName(GenUtils.getBusinessName(tableName));
            genTable.setFunctionName(GenUtils.replaceText(tableName));
            genTable.setFunctionAuthor(GenConfig.getAuthor());
            genTable.setCreateBy(operName);
            genTable.setTableName(tableName);
            genTable.setTableComment(tableResult.stream().filter(p->p.get("table_name").equals(tableName)).findFirst().get().get("table_comment").toString());
            genTable.setGenPath("H:\\abilities-code\\abilities-system\\src");
            int row = genTableMapper.insertGenTable(genTable);
            if (row > 0) {
                for (Map map : singleMap.get(tableName)) {
                    GenTableColumn genTableColumn = new GenTableColumn();
                    genTableColumn.setColumnName(map.get("column_name").toString());
                    genTableColumn.setColumnType(map.get("column_type").toString());
                    genTableColumn.setColumnComment(map.get("column_comment").toString());
                    genTableColumn.setIsIncrement(map.get("is_increment").toString());
                    genTableColumn.setIsPk(map.get("is_pk").toString());
                    genTableColumn.setIsRequired(map.get("is_required").toString());
                    genTableColumn.setSort(Integer.valueOf(map.get("sort").toString()));
                    GenUtils.initColumnField(genTableColumn, genTable);
                    genTableColumnMapper.insertGenTableColumn(genTableColumn);
                }
            }
        }
        for(String tableName:tableNames)
        {
            genTableService.generatorCode(tableName);
        }
        jdbcUtil.release();
    }
}
